import React, { useState } from 'react';
import { Button, Table, Modal, message,Form,Input } from 'antd';
import './index.scss'
import { useEffect } from 'react';
import {getAdmins,addAdmin} from '../../../utils/request';


const currentAdminId = 1;

const AdminInfo = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedAdmin, setSelectedAdmin] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [showCheckbox, setShowCheckbox] = useState(false);
  const [adminData, setAdminData] = useState([]);
  const [isAddModalVisible, setIsAddModalVisible] = useState(false); // 新增弹窗状态
  const [addForm] = Form.useForm(); //

  useEffect(() => {
      getAdmins('admin')
          .then(data => {
            setAdminData(data);
          })
          .catch(err => {
              console.error(err);
              message.error('获取用户数据失败');
          });
  }, []);

  const rowClassName = (record) => {
    if (record.id === currentAdminId) {
      return 'highlight-row-admininfo';
    }
    return '';
  };

  const handleAdd = () => {
    setIsAddModalVisible(true); // 触发添加弹窗
  };

  const handleDelete = () => {
    if (showCheckbox) {
      if (selectedRowKeys.length > 0) {
        message.info(`已删除 ${selectedRowKeys.length} 条记录`);
        const newData = data.filter(item => !selectedRowKeys.includes(item.key));
        setData(newData);
      } else {
        message.warning('请选择要删除的管理员');
      }
      setShowCheckbox(false);
      setSelectedRowKeys([]);
    } else {
      setShowCheckbox(true);
    }
  };

  const handleMore = (record) => {
    setSelectedAdmin(record);
    setIsModalVisible(true);
  };

  const handleAddAdmin = async () => {
    try {
      const values = await addForm.validateFields();
      const response = await addAdmin(values);
      if (response.success) {
        message.success('管理员添加成功');
        setIsAddModalVisible(false);
        // 刷新管理员列表
        getAdmins('admin').then(data => setAdminData(data));
      }
    } catch (error) {
      message.error('添加失败：' + (error.response?.data?.message || '网络错误'));
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '用户名', dataIndex: 'username', key: 'username' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    { title: '入职时间', dataIndex: 'joinDate', key: 'joinDate' },
    { title: '信息权限', dataIndex: 'permission', key: 'permission' },
    { 
      title: '更多', 
      key: 'more', 
      render: (_, record) => (
        <a style={{ color: 'blue' }} onClick={() => handleMore(record)}>
          更多
        </a>
      ),
    },
  ];

  const [data, setData] = useState(Array.from({ length: 100 }, (_, index) => ({ 
    key: index,
    id: index + 1,
    username: `管理员${index + 1}`,
    email: `admin${index + 1}@example.com`,
    joinDate: '2023-01-01',
    permission: '高级',
  })));

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys) => {
      setSelectedRowKeys(keys);
    },
    columnWidth: '50px',
    hideDefaultSelections: true,
    selections: [],
    preserveSelectedRowKeys: false,
  };

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'inline-block' }}>
        <Button onClick={handleAdd} >添加</Button>
        <Button
          style={{ marginLeft: 8, backgroundColor: showCheckbox && selectedRowKeys.length > 0 ? 'red' : '', color: showCheckbox && selectedRowKeys.length > 0 ? 'white' : '' }}
          onClick={handleDelete}
        >
          {showCheckbox ? '确认删除' : '删除'}
        </Button>
      </div>
      <Modal
        title="添加管理员"
        visible={isAddModalVisible}
        onOk={handleAddAdmin}
        onCancel={() => setIsAddModalVisible(false)}
        okText="添加"
        cancelText="取消"
      >
        <Form form={addForm} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
            style={{ width:'77%' }}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
            style={{ width:'80%' }}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
            style={{ width:'80%' }}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
        </Form>
      </Modal>
      <Table
        columns={columns}
        dataSource={adminData}
        pagination={{ pageSize: 20 }}
        rowSelection={showCheckbox ? rowSelection : null}
        rowClassName={rowClassName}
      />
      <Modal
        title="管理员简历"
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        {selectedAdmin && (
          <div>
            <p>ID: {selectedAdmin.id}</p>
            <p>用户名: {selectedAdmin.username}</p>
            <p>邮箱: {selectedAdmin.email}</p>
            <p>入职时间: {selectedAdmin.joinDate}</p>
            <p>信息权限: {selectedAdmin.permission}</p>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AdminInfo;